//
//  PaymentAmountController.m
//  JiFengDaRen
//
//  Created by Lyc on 2017/11/6.
//  Copyright © 2017年 SH_iOS. All rights reserved.
//
#import "SHNoticeView.h"
#import "HomeNoticeModel.h"

#import "PayBankListView.h"
#import "SHCompleteCustInfoContorller.h" //完善用户实名 银行卡信息
#import "BaseToolViewController.h"//网页
#import "SHAddPayBankCardController.h"//添加付款卡
#import "SHBindCardViewController.h"//绑卡页面
#import "SHQuickPayViewController.h"//web快捷支付
#import "CSQrcodeWebViewController.h"//二维码网页
#import "SHRBImageUploadController.h"//荣邦完善用户信息
#import "SHModifyUnionCashCardController.h"//完善收款卡信息
#import "PaymentAmountController.h"
#import "SHPayViewModel.h"

@interface PaymentAmountController ()<UITextFieldDelegate,PayBankListViewDelegate>

@property(nonatomic,strong)UITextField *moneyTf;
@property(nonatomic,strong)UIButton  *cashPayButton;
//@property(nonatomic,strong)SHNoticeView * noticeView;//通知跑马灯
@property(nonatomic,strong)HomeNoticeModel *noticeModel;//通知模型
@property(nonatomic,getter=isQueryStatus)BOOL queryStatus;//是否已经查询用户完善状态
@property(nonatomic)BOOL authStatus;//是否需要完善身份证信息
@property(nonatomic)BOOL bankStatus;//是否需要完善银行卡信息
@end

@implementation PaymentAmountController
{
    UIView *_bgView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    
}

- (void)setCashPaymentType:(SHCashPaymentType)cashPaymentType{
    
    _cashPaymentType = cashPaymentType;
    
}

#pragma mark - 初始化UI
- (void)createUI{
    
    self.view.backgroundColor = KBASEBGCOLOR;
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, __I6Height(11), KScreenWidth, __I6Height(50))];
    
    bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgView];
    _bgView = bgView;
    
    UILabel *payLabel = [[UILabel alloc]init];
    payLabel.textAlignment = NSTextAlignmentCenter;
    payLabel.text = @"支付金额";
    payLabel.font = KSystemFont(__I6Height(16));
    payLabel.textColor = KSHTEXTCOLOR;
    [bgView addSubview:payLabel];
    
    self.moneyTf = [[UITextField alloc]init];
    self.moneyTf.textColor = KSHTEXTCOLOR;
    self.moneyTf.delegate = self;
    self.moneyTf.keyboardType = UIKeyboardTypeDecimalPad;
    self.moneyTf.placeholder = @"请输入支付金额";
    self.moneyTf.clearButtonMode = UITextFieldViewModeAlways;
    self.moneyTf.textAlignment = NSTextAlignmentLeft;
    self.moneyTf.font = KSystemFont(__I6Width(16));
    [bgView addSubview: self.moneyTf];
    
    self.cashPayButton = [[UIButton alloc]init];
    self.cashPayButton.userInteractionEnabled = YES;
    [self.cashPayButton setBackgroundImage:[UIImage imageNamed:@"btn_bg"] forState:UIControlStateNormal];
    [self.cashPayButton setTitleColor:[UIColor colorWithHexString:@"333333"] forState:UIControlStateNormal];
    [ self.cashPayButton setTitle:@"确认支付" forState:UIControlStateNormal];
    self.cashPayButton.titleLabel.font = KSystemFont(__I6Width(16));
    [ self.cashPayButton addTarget:self action:@selector(cashPayButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.cashPayButton];
    
    [payLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(bgView.mas_centerY);
        make.left.mas_equalTo(bgView.mas_left).mas_offset(__I6Width(15));
        make.width.mas_equalTo(__I6Width(80));
        make.height.mas_equalTo(__I6Height(16));
    }];
    
    [self.moneyTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(bgView.mas_centerY);
        make.left.mas_equalTo(payLabel.mas_right).mas_offset(__I6Width(15));
        make.right.mas_equalTo(bgView.mas_right).mas_offset(__I6Width(-15));
        make.height.mas_equalTo(__I6Height(40));
    }];
    
    [ self.cashPayButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(bgView.mas_bottom).mas_offset(__I6Height(50));
        make.centerX.mas_equalTo(bgView.mas_centerX);
    }];
    
}


#pragma mark - 文本框代理
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.moneyTf resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark --- 文本框代理
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if (textField == self.moneyTf) {
        NSScanner      *scanner    = [NSScanner scannerWithString:string];
        NSCharacterSet *numbers;
        NSRange         pointRange = [textField.text rangeOfString:@"."];
        
        if ( (pointRange.length > 0) && (pointRange.location < range.location  || pointRange.location > range.location + range.length) )
        {
            numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
        }
        else
        {
            numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
        }
        
        if ( [textField.text isEqualToString:@""] && [string isEqualToString:@"."] )
        {
            return NO;
        }
        
        short remain = 2; //默认保留2位小数
        
        NSString *tempStr = [textField.text stringByAppendingString:string];
        NSUInteger strlen = [tempStr length];
        if(pointRange.length > 0 && pointRange.location > 0){ //判断输入框内是否含有“.”。
            if([string isEqualToString:@"."]){ //当输入框内已经含有“.”时，如果再输入“.”则被视为无效。
                return NO;
            }
            if(strlen > 0 && (strlen - pointRange.location) > remain+1){ //当输入框内已经含有“.”，当字符串长度减去小数点前面的字符串长度大于需要要保留的小数点位数，则视当次输入无效。
                return NO;
            }
        }
        
        NSRange zeroRange = [textField.text rangeOfString:@"0"];
        if(zeroRange.length == 1 && zeroRange.location == 0){ //判断输入框第一个字符是否为“0”
            if(![string isEqualToString:@"0"] && ![string isEqualToString:@"."] && [textField.text length] == 1){// 当输入框只有一个字符并且字符为“0”时，再输入不为“0”或者“.”的字符时，则将此输入替换输入框的这唯一字符。
                textField.text = string;
                return NO;
            }else{
                if(pointRange.length == 0 && pointRange.location > 0){ //当输入框第一个字符为“0”时，并且没有“.”字符时，如果当此输入的字符为“0”，则视当此输入无效。
                    if([string isEqualToString:@"0"]){
                        return NO;
                    }
                }
            }
        }
        
        NSString *buffer;
        if ( ![scanner scanCharactersFromSet:numbers intoString:&buffer] && ([string length] != 0) )
        {
            return NO;
        }
        
    }
    return YES;
}


#pragma mark - 发起收款
- (void)cashPayButtonAction:(UIButton *)btn{
    
    [self.moneyTf resignFirstResponder];
    if ([self checkCasherAmount]){//校验收款金额
        
        //检查用户实名绑卡状态
        [self checkUserRealNameBankCard];
        
    }
}


#pragma mark - 校验收款金额的合法性
- (BOOL)checkCasherAmount{
    
    if ([self.moneyTf.text containsString:@"."]) {
        if( [[[self.moneyTf.text componentsSeparatedByString:@"."] lastObject] length] == 0){
            [self.view makeToast:@"非法金额" duration:2 position:@"center"];
            return NO;
        }
    }
    
    if (self.moneyTf.text.length == 0) {
        [self.view makeToast:@"请输入支付金额" duration:2 position:@"center"];
        return NO;
    }
    
    if([ self.moneyTf.text floatValue] > 50000){
        
        [self.view makeToast: @"银联支付收款最大支持金额5万元"duration:2 position:@"center"];
        return NO;
    }

    return  YES;
    
}


#pragma mark - 检查用户实名认证 绑卡状态
- (void)checkUserRealNameBankCard{
    
    [self.moneyTf resignFirstResponder];
    
    MBProgressHUD* hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [hud hideAnimated:YES afterDelay:1.f];
    
    [SHUserCenterHttp finderSHUserBindCardStatusSuccess:^(int status) {
        //发起支付
        [self userCasherPay];
        
    } complection:^(int status) {
        // 收款卡（储蓄卡）
        SHBindCardViewController *bindingBankCardVc = [[SHBindCardViewController  alloc]init];
        bindingBankCardVc.usingType = SHCashCardUsingTypeShAddCard;
        [self.navigationController pushViewController:bindingBankCardVc animated:YES];
        
    } failure:^(int status) {
        //实名认证
        [self gotoCertificationVc];
        
    }];
/**** 坑 —— 付款卡也可以是储蓄卡。 收款卡也可以是信用卡。BUG ***/
    
}


#pragma mark - 跳转到实名认证页面
- (void)gotoCertificationVc{
    
    [self.navigationController pushViewController:[[SHRealNameViewController alloc]init] animated:YES];
}



#pragma mark - 根据支付方式发起收款
- (void)userCasherPay{
   
    if (self.cashPaymentType == 0) {
        [SHPayViewModel TenpaytongGetApplyViewSuccess:^(int status) {
            if (status == 1) {
                [self popCashPayBankListViewChoices:@(2) andCardType:12];
            }else{
                [self popCashPayBankListViewChoices:@(1) andCardType:11];
            }
        }];
    }else{
        [self popCashPayBankListViewChoices:@(2) andCardType:12];
    }
}



#pragma mark - 弹出收款卡列表
- (void)popCashPayBankListViewChoices:(NSNumber *)cNumber andCardType:(int)cardType{
    
    PayBankListView *payBankListView = [[PayBankListView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight) usingChoices:cNumber bankCardType:cardType showAllBankCard:NO];
    
    payBankListView.delegate = self;
    [payBankListView showCustomView];
    
}


#pragma mark - 银行卡弹出列表代理
- (void)payBankListView:(PayBankListView *)view bankCardCode:(NSString *)bankCardCode bankCardId:(NSString *)bankCardId usingChoices:(NSNumber *)usingChoices{
    
    if ([usingChoices isEqualToNumber:@(1)]) {//收款卡
        
        if (![bankCardCode isEqualToString:@"0"]) {

            if (self.cashPaymentType == 0) {
       
                [SHPayViewModel TenpaytongGetReplyWith:bankCardCode andWithSuccess:^(id success) {
                    NSLog(@"success :%@",success);
                    
                    if ([success[@"success"] boolValue] == YES) {
                        [self.view makeToast:@"报件成功" duration:2 position:@"center"];

                    }else{
                        [self.view makeToast:success[@"data"] duration:2 position:@"center"];
                    }
                }];
            }
            
        }else{//添加收款卡
            
            SHBindCardViewController *bindingBankCardVc = [[SHBindCardViewController  alloc]init];
            bindingBankCardVc.usingType = SHCashCardUsingTypeShAddCard;
            [self.navigationController pushViewController:bindingBankCardVc animated:YES];
        }
        
    }else{//付款卡
      
        if (![bankCardCode isEqualToString:@"0"]) {
            
            if (self.cashPaymentType == 0) {
                NSMutableDictionary * dic = [NSMutableDictionary dictionary];
                [dic setValue:bankCardCode forKey:@"card_code"];
                [dic setValue:self.moneyTf.text forKey:@"money"];
                [SHPayViewModel TenpaytongCreate_orderWithDictionary:dic andWithSuccess:^(id success) {
                    
                    if ([success[@"success"] boolValue] == YES) {
                        SHQuickPayViewController *sqPavVc = [[SHQuickPayViewController alloc]init];
                        if ([success[@"data"][@"code"] integerValue] == 1) {
                            sqPavVc.requestType = SHQuickPayWebViewRequestTypeUrl;
                            sqPavVc.url = success[@"data"][@"pay_url"];
                        }else{
                            sqPavVc.requestType = SHQuickPayWebViewRequestTypeHtmlPage;
                            sqPavVc.page = success[@"data"][@"page"];
                        }
                        
                        [self.navigationController pushViewController:sqPavVc animated:YES];
                    }else{
                        [self.view makeToast:success[@"data"] duration:2 position:@"center"];
                    }
                   
                }];
            }else{
                
                NSMutableDictionary * dic = [NSMutableDictionary dictionary];
                [dic setValue:@"1025" forKey:@"card_over_data"];
                [dic setValue:@"578" forKey:@"cvn_num"];
                [dic setValue:bankCardCode forKey:@"card_no"];
                [dic setValue:self.moneyTf.text forKey:@"total_fee"];

                [SHPayViewModel Huizhifupay_add_orderDictionary:dic andWithSuccess:^(id success) {
                    if ([success[@"success"] boolValue] == YES) {
                        
                        SHQuickPayViewController *sqPavVc = [[SHQuickPayViewController alloc] init];
                        sqPavVc.requestType = SHQuickPayWebViewRequestTypeHtml;
                        sqPavVc.page = success[@"data"];
                        [self.navigationController pushViewController:sqPavVc animated:YES];

                    }else{
                        [self.view makeToast:success[@"data"] duration:2 position:@"center"];
                    }
                } Failure:^(NSError *error) {
                    
                }];
            }
          
        }else{
            
            SHAddPayBankCardController *add = [[SHAddPayBankCardController alloc]init];
            [self.navigationController pushViewController:add animated:YES];
        }
    }
}




@end
